package com.exp.security.web;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.UUID;
import com.exp.security.constant.AppConstants;
import com.exp.security.vo.CaptchaVO;
import com.exp.security.vo.R;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangxj
 * @date 2025/1/7
 * @Description
 */
@RestController
public class CaptChaController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/captcha")
    public R<CaptchaVO> getCaptcha(HttpServletRequest request, HttpServletResponse response){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 32);
        String code = lineCaptcha.getCode();
        // 验证码图片
        String imgBase64 = lineCaptcha.getImageBase64();
        // 创建验证码对象
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setId(UUID.randomUUID().toString());
        captchaVO.setBase64(imgBase64);
        // 缓存验证码, 10 分钟有效
        stringRedisTemplate.opsForValue().set(AppConstants.CAPTCHA_PREFIX + captchaVO.getId(), code, 10 , TimeUnit.MINUTES);
        return R.data(captchaVO, "生成验证码成功");
    }

}
